package com.share.infrastructure.persistent.repository;

import com.share.domain.task.model.TaskEntity;
import com.share.domain.task.repository.ITaskRepository;
import com.share.infrastructure.event.EventPublisher;
import com.share.infrastructure.persistent.dao.ITaskDao;
import com.share.infrastructure.persistent.po.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Repository
@Slf4j
public class TaskRepository implements ITaskRepository {
    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher eventPublisher;

    @Override
    public List<com.share.domain.task.model.TaskEntity> queryNoSendMessageTaskList() {
        List<Task> tasks = taskDao.queryNoSendMessageTaskList();
        List<com.share.domain.task.model.TaskEntity> taskEntities = new ArrayList<>(tasks.size());
        for (Task task : tasks){
            com.share.domain.task.model.TaskEntity taskEntity = com.share.domain.task.model.TaskEntity.builder()
                    .messageId(task.getMessageId())
                    .message(task.getMessage())
                    .topic(task.getTopic())
                    .userId(task.getUserId())
                    .build();
            taskEntities.add(taskEntity);
        }
        return taskEntities;
    }

    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(),taskEntity.getMessage());
    }

    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        Task task = new Task();
        task.setMessageId(messageId);
        task.setUserId(userId);
        int i = taskDao.updateTaskSendMessageCompleted(task);
        log.info("updateTaskSendMessageCompleted执行情况:{}",i);

    }

    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        Task task = new Task();
        task.setMessageId(messageId);
        task.setUserId(userId);
        taskDao.updateTaskSendMessageFail(task);
    }
}
